package shared.util;

import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5CryptographyUtil {
    private static Logger logger = Logger.getLogger(MD5CryptographyUtil.class);

    public static String encrypt(String textToEncrypt) {
        return encrypt(textToEncrypt, "MD5", "UTF-16");
    }

    private static String encrypt(String textToEncrypt, String algorithm, String encoding) {
        String hashValue = null;
        try {
            MessageDigest msgDigest = MessageDigest.getInstance(algorithm);
            msgDigest.update(textToEncrypt.getBytes(encoding));
            byte rawByte[] = msgDigest.digest();
            hashValue = (new BASE64Encoder()).encode(rawByte);
        } catch (NoSuchAlgorithmException e) {
            logger.error("Error  occurred while encryting string " + encoding + " > " + e.getMessage());
        } catch (UnsupportedEncodingException e) {
            logger.error("Error  occurred while encryting string " + encoding + " > " + e.getMessage());
        }
        return hashValue;
    }

    public static void main(String[] args) {
        System.out.println("*************************");
        System.out.println("admin: " + encrypt("admin"));
        System.out.println("employee: " + encrypt("employee"));
        System.out.println("foreman: " + encrypt("foreman"));
    }
}
